package com.gearbox.core.driver.impl;

import com.gearbox.core.configuration.EcsConfiguration;
import com.gearbox.core.driver.EcsHandler;
import com.gearbox.core.http.HttpConfigFactory;
import com.gearbox.core.util.SdkResponseAssertion;
import com.huaweicloud.sdk.ecs.v2.EcsClient;
import com.huaweicloud.sdk.ecs.v2.model.ServerDetail;
import com.huaweicloud.sdk.ecs.v2.model.ShowServerRequest;
import com.huaweicloud.sdk.ecs.v2.model.ShowServerResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Locale;

import javax.annotation.PostConstruct;

@Component
public class EcsHandlerImpl implements EcsHandler {
    private static final Logger LOG = LoggerFactory.getLogger(EcsHandlerImpl.class);

    private final EcsConfiguration ecsConfiguration;

    private final HttpConfigFactory configFactory;

    EcsClient ecsClient;

    public EcsHandlerImpl(EcsConfiguration ecsConfiguration, HttpConfigFactory configFactory) {
        this.ecsConfiguration = ecsConfiguration;
        this.configFactory = configFactory;
    }

    @PostConstruct
    public void init() {
        initEcsClient();
    }

    private void initEcsClient() {
        ecsClient = EcsClient.newBuilder()
            .withHttpConfig(configFactory.getHttpConfig())
            .withCredential(configFactory.getBasicCredentials())
            .withEndpoint(ecsConfiguration.getEndpoint())
            .build();
    }

    @Override
    public ServerDetail getInstanceDetailById(String id) {
        LOG.info("show server begin, id={}", id);
        ShowServerResponse resp = ecsClient.showServer(buildShowServerRequest(id));
        LOG.info("show server end, resp={}", resp);
        SdkResponseAssertion.assertError(resp, String.format(Locale.ROOT, "show server %s failed", id));
        return resp.getServer();
    }

    ShowServerRequest buildShowServerRequest(String id) {
        return new ShowServerRequest().withServerId(id);
    }
}
